<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="tong.li&#39;s blog">
  <meta name="keyword" content="彤哥哥博客，95后技术爱好者,现就职于同程旅行/同程艺龙上海分公司，专注于互联网技术分享的平台。">
  
    <link rel="shortcut icon" href="/css/images/icon.png">
  
  <title>
    
      【Java并发编程实战】-浅谈volatile内存可见性 | 彤哥哥的博客
    
  </title>
  <link href="https://cdn.staticfile.org/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="https://cdn.staticfile.org/highlight.js/9.12.0/styles/tomorrow-night.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
  <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://cdn.staticfile.org/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="https://cdn.staticfile.org/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdn.staticfile.org/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


  
  
    
<script src="/js/local-search.js"></script>


<meta name="generator" content="Hexo 5.4.2"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>
  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>彤哥哥的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/series/" class="item-link">分类</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/project/" class="item-link">项目</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于</a>
          
        </li>
      
      
        <li class="menu-item menu-item-search right-list">
    <a role="button" class="popup-trigger">
        <i class="fa fa-search fa-fw"></i>
    </a>
</li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/series/" class="menu-link">分类</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/project/" class="menu-link">项目</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于</a>
            
          </li>
        
      </ul>
    </div>
    
      <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
            <span class="search-icon">
                <i class="fa fa-search"></i>
            </span>
            <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off"
                    placeholder="Please enter your keyword(s) to search." spellcheck="false"
                    type="search" class="search-input">
            </div>
            <span class="popup-btn-close">
                <i class="fa fa-times-circle"></i>
            </span>
        </div>
        <div id="search-result">
            <div id="no-result">
                <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
            </div>
        </div>
    </div>
</div>
    
  </div>
</header>

    <div id="article-banner">
  <h2>【Java并发编程实战】-浅谈volatile内存可见性</h2>
  <p class="post-date">2018-06-03</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><p>volatile这个关键字大家都听过，看过许多源码也用过，这个关键字备受争议，很多人基于表面理解而导致在实际开发过生中大肆误用，暴露出各式各样的问题，让人摸不着头脑，今天我们来好好理解一下volatile。</p>
<ul>
<li>百度百科:volatile是一个类型修饰符.<strong>volatile</strong>的作用是作为指令关键字，确保本条指令不会因编译器的优化而省略，且要求每次直接读值;</li>
<li>volatile是Java虚拟机提供的轻量级同步机制的关键字，使被修饰的变量在多个线程可见；</li>
<li>volatile变量具有 synchronized 的可见性特性，与synchronize有相似的同步功能，但不具备原子特性，在多线程并发下是不安全的。</li>
</ul>
<h2 id="两种特性"><a href="#两种特性" class="headerlink" title="两种特性"></a>两种特性</h2><h3 id="特性归纳"><a href="#特性归纳" class="headerlink" title="特性归纳"></a>特性归纳</h3><p>当一个变量被定义成volatile之后，它将具备如下两种特性:</p>
<blockquote>
<p>保证此变量对所有线程的可见性。即指当一条线程修改了这个变量的值，新值对于其他线程来说是可以立即感知的，而相比之下，普通变量不能做到这点，变量值在线程间传递均需要通过主内存来完成。比如线程1修改a的值，然后向主内存进行回写，另外一条线程2在线程1回写完成了之后再从主内存进行读取操作，新变量的值才会对线程2可见。</p>
</blockquote>
<blockquote>
<p>禁止指令重排序优化。普通变量仅仅会保证在该方法的执行过程中所有依赖赋值结果的地方都能获取到正确的结果，而不能保证变量赋值操作的顺序与程序代码中的执行顺序一致。因为在一个线程的方法执行过程中无法感知到这点，这就是所谓的“线程内表现为串行的语义”(Within-Thread As-If-Serial Semantics)。</p>
</blockquote>
<h3 id="代码示例"><a href="#代码示例" class="headerlink" title="代码示例"></a>代码示例</h3><h4 id="多线程并发安全"><a href="#多线程并发安全" class="headerlink" title="多线程并发安全"></a>多线程并发安全</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> tong.li</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: volatile只保证内存间线程可见性,并不保证线程安全性</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> 2018-06-12 11:11:23</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">VolatileTest</span> &#123;</span><br><span class="line"></span><br><span class="line">	<span class="comment">//共享变量</span></span><br><span class="line">    <span class="keyword">public</span>  <span class="keyword">volatile</span> <span class="type">int</span> <span class="variable">num</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//线程数量</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">int</span> <span class="variable">THREAD_COUNT</span> <span class="operator">=</span> <span class="number">20</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span>  <span class="keyword">void</span> <span class="title function_">add</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="comment">//num进行非原子操作</span></span><br><span class="line">        num++;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">final</span> <span class="type">VolatileTest</span> <span class="variable">test</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">VolatileTest</span>();</span><br><span class="line">        <span class="comment">//创建20个线程</span></span><br><span class="line">        Thread[] threads = <span class="keyword">new</span> <span class="title class_">Thread</span>[THREAD_COUNT];</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; THREAD_COUNT ; i++) &#123;</span><br><span class="line">           threads[i] = <span class="keyword">new</span> <span class="title class_">Thread</span>(() -&gt; &#123;</span><br><span class="line">                <span class="comment">//当前线程操作10000次对共享变量num进行自加操作</span></span><br><span class="line">                <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">j</span> <span class="operator">=</span> <span class="number">0</span>; j &lt; <span class="number">10000</span>; j++) &#123;</span><br><span class="line">                    test.add();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="comment">//启动当前线程</span></span><br><span class="line">            threads[i].start();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//活动线程的当前线程的线程组中的数量大于1时,执行线程让步,让活动的线程尽可能执行完</span></span><br><span class="line">       <span class="comment">// while (Thread.activeCount() &gt; 1) &#123;</span></span><br><span class="line">         <span class="comment">//   Thread.yield();</span></span><br><span class="line">        <span class="comment">//&#125;</span></span><br><span class="line">        <span class="comment">//打印最终结果,结果多数小于200000,为什么呢?</span></span><br><span class="line">         System.out.println(<span class="string">&quot;num = &quot;</span> + test.num);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果如下:</p>
<ul>
<li><p>第1次</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">num = 132203</span><br></pre></td></tr></table></figure></li>
<li><p>第2次</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">num = 160740</span><br></pre></td></tr></table></figure></li>
<li><p>第3次</p>
<figure class="highlight sh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">num = 187482</span><br></pre></td></tr></table></figure></li>
</ul>
<p>上述代码创建20个线程，每个线程对num进行10000次自增操作，如果上述代码正确并发（不考虑线程安全问题）的情况下，最后的结果应该是200000，但是为实际三次运行结果令人匪夷所思，多次的运行结果大部分情况下都是小于200000，这是为什么呢？</p>
<p>我们都知道num++是非原子性操作，我们可以尝试进行javap反编译上述代码一探究竟：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br></pre></td><td class="code"><pre><span class="line">Yeamin:java mac$ javap -c VolatileTest</span><br><span class="line"></span><br><span class="line">Compiled from &quot;VolatileTest.java&quot;</span><br><span class="line"></span><br><span class="line">public class VolatileTest &#123;</span><br><span class="line"></span><br><span class="line">  public volatile int num;</span><br><span class="line"></span><br><span class="line">  public static final int THREAD_COUNT;</span><br><span class="line"></span><br><span class="line">  public VolatileTest();</span><br><span class="line"></span><br><span class="line">   Code:</span><br><span class="line">       0: aload_0</span><br><span class="line"></span><br><span class="line">       1: invokespecial #1                  // Method java/lang/Object.&quot;&lt;init&gt;&quot;:()V</span><br><span class="line"></span><br><span class="line">       4: aload_0</span><br><span class="line"></span><br><span class="line">       5: iconst_0</span><br><span class="line"></span><br><span class="line">       6: putfield      #2                  // Field num:I</span><br><span class="line"></span><br><span class="line">       9: return</span><br><span class="line"></span><br><span class="line">  public void add();</span><br><span class="line"></span><br><span class="line">    Code:</span><br><span class="line">       0: aload_0</span><br><span class="line"></span><br><span class="line">       1: dup</span><br><span class="line"></span><br><span class="line">       2: getfield      #2                  // Field num:I</span><br><span class="line"></span><br><span class="line">       5: iconst_1</span><br><span class="line"></span><br><span class="line">       6: iadd</span><br><span class="line"></span><br><span class="line">       7: putfield      #2                  // Field num:I</span><br><span class="line"></span><br><span class="line">      10: return</span><br><span class="line"></span><br><span class="line">  public static void main(java.lang.String[]);</span><br><span class="line"></span><br><span class="line">    Code:</span><br><span class="line"></span><br><span class="line">       0: new           #3                  // class VolatileTest</span><br><span class="line"></span><br><span class="line">       3: dup</span><br><span class="line"></span><br><span class="line">       4: invokespecial #4                  // Method &quot;&lt;init&gt;&quot;:()V</span><br><span class="line"></span><br><span class="line">       7: astore_1</span><br><span class="line"></span><br><span class="line">       8: bipush        20</span><br><span class="line"></span><br><span class="line">      10: anewarray     #5                  // class java/lang/Thread</span><br><span class="line"></span><br><span class="line">      13: astore_2</span><br><span class="line"></span><br><span class="line">      14: iconst_0</span><br><span class="line"></span><br><span class="line">      15: istore_3</span><br><span class="line"></span><br><span class="line">      16: iload_3</span><br><span class="line"></span><br><span class="line">      17: bipush        20</span><br><span class="line"></span><br><span class="line">      19: if_icmpge     52</span><br><span class="line"></span><br><span class="line">      22: aload_2</span><br><span class="line"></span><br><span class="line">      23: iload_3</span><br><span class="line"></span><br><span class="line">      24: new           #5                  // class java/lang/Thread</span><br><span class="line"></span><br><span class="line">      27: dup</span><br><span class="line"></span><br><span class="line">      28: new           #6                  // class VolatileTest$1</span><br><span class="line"></span><br><span class="line">      31: dup</span><br><span class="line"></span><br><span class="line">      32: aload_1</span><br><span class="line"></span><br><span class="line">      33: invokespecial #7                  // Method VolatileTest$1.&quot;&lt;init&gt;&quot;:(LVolatileTest;)V</span><br><span class="line"></span><br><span class="line">      36: invokespecial #8                  // Method java/lang/Thread.&quot;&lt;init&gt;&quot;:(Ljava/lang/Runnable;)V</span><br><span class="line"></span><br><span class="line">      39: aastore</span><br><span class="line"></span><br><span class="line">      40: aload_2</span><br><span class="line"></span><br><span class="line">      41: iload_3</span><br><span class="line"></span><br><span class="line">      42: aaload</span><br><span class="line"></span><br><span class="line">      43: invokevirtual #9                  // Method java/lang/Thread.start:()V</span><br><span class="line"></span><br><span class="line">      46: iinc          3, 1</span><br><span class="line"></span><br><span class="line">      49: goto          16</span><br><span class="line"></span><br><span class="line">      52: invokestatic  #10                 // Method java/lang/Thread.activeCount:()I</span><br><span class="line"></span><br><span class="line">      55: iconst_1</span><br><span class="line"></span><br><span class="line">      56: if_icmple     65</span><br><span class="line"></span><br><span class="line">      59: invokestatic  #11                 // Method java/lang/Thread.yield:()V</span><br><span class="line"></span><br><span class="line">      62: goto          52</span><br><span class="line"></span><br><span class="line">      65: getstatic     #12                 // Field java/lang/System.out:Ljava/io/PrintStream;</span><br><span class="line"></span><br><span class="line">      68: new           #13                 // class java/lang/StringBuilder</span><br><span class="line"></span><br><span class="line">      71: dup</span><br><span class="line"></span><br><span class="line">      72: invokespecial #14                 // Method java/lang/StringBuilder.&quot;&lt;init&gt;&quot;:()V</span><br><span class="line"></span><br><span class="line">      75: ldc           #15                 // String num =</span><br><span class="line"></span><br><span class="line">      77: invokevirtual #16                 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;</span><br><span class="line"></span><br><span class="line">      80: aload_1</span><br><span class="line"></span><br><span class="line">      81: getfield      #2                  // Field num:I</span><br><span class="line"></span><br><span class="line">      84: invokevirtual #17                 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;</span><br><span class="line"></span><br><span class="line">      87: invokevirtual #18                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;</span><br><span class="line"></span><br><span class="line">      90: invokevirtual #19                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V</span><br><span class="line"></span><br><span class="line">      93: return</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在上述反编译的字节码分析得知，num++不是一个原子操作，即线程不安全，可以将num++简单分解成以下几个步骤:</p>
<ol>
<li><p>从内存中取出num的值；</p>
</li>
<li><p>计算num的值；</p>
</li>
<li><p>将num的值刷新到主内存中</p>
</li>
</ol>
<p>add()方法有6条指令（每个指令可能含有多个底层指令操作，只为研究，并不准确，要想准确研究建议使用-XX:+PrintAssembly参数输出反汇编），其中return指令可以忽略不计，因为不是num++产生的。</p>
<ol>
<li>aload_0：在非静态方法中，aload_0 表示对this的操作，在static 方法中，aload_0表示对方法的第一参数的操作；</li>
<li>dup：复制操作数栈顶值，并将其压入栈顶，在这里是将当前VolatileTest下new对象压入栈顶；</li>
<li>getfield/getstatic：将栈顶的对象第二个实例字段压入栈顶，即将num的值压入栈顶，此时num的值是最新的；</li>
<li>iconst_1：将int型(1)推送至栈顶，即把常量1压入栈顶；</li>
<li><strong>iadd：把操作数栈中的前两个int值出栈并相加,操作过后只在stack中保留结果，即使num当前值+1保留在栈中，这里多线程时候可能出现问题，其他线程相加的结果会覆盖当前栈顶的结果，因而返回较小的结果</strong>。</li>
<li>putfield：将最终的栈顶结果的值刷新到主内存中；</li>
<li>return：栈中的数据返回后，结束方法</li>
</ol>
<h4 id="禁止指令重排序"><a href="#禁止指令重排序" class="headerlink" title="禁止指令重排序"></a>禁止指令重排序</h4><p>volatile关键字禁止指令重排序有两层意思：</p>
<ul>
<li>当程序执行到volatile变量的读操作或者写操作时，在其前面的操作的更改肯定全部已经进行，且结果已经对后面的操作可见；在其后面的操作肯定还没有进行；</li>
<li>在进行指令优化时，不能将在对volatile变量访问的语句放在其后面执行，也不能把volatile变量后面的语句放到其前面执行。</li>
</ul>
<p>举个实例，请看下面的代码:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//x、y为非volatile变量</span></span><br><span class="line"><span class="comment">//flag为volatile变量</span></span><br><span class="line"><span class="type">int</span> <span class="variable">x</span> <span class="operator">=</span> <span class="number">2</span>;        <span class="comment">//语句1</span></span><br><span class="line"><span class="type">int</span> <span class="variable">y</span> <span class="operator">=</span> <span class="number">0</span>;        <span class="comment">//语句2</span></span><br><span class="line"><span class="keyword">volatile</span> <span class="type">boolean</span> <span class="variable">flag</span> <span class="operator">=</span> <span class="literal">true</span>;  <span class="comment">//语句3</span></span><br><span class="line"><span class="type">int</span> <span class="variable">x</span> <span class="operator">=</span> <span class="number">4</span>;         <span class="comment">//语句4</span></span><br><span class="line"><span class="type">int</span> <span class="variable">y</span> <span class="operator">=</span> -<span class="number">1</span>;       <span class="comment">//语句5</span></span><br></pre></td></tr></table></figure>

<p>由于flag变量为volatile变量，那么在进行指令重排序的过程的时候，不会将语句3放到语句1、语句2前面，也不会讲语句3放到语句4、语句5后面。但是要注意语句1和语句2的顺序、语句4和语句5的顺序是不作任何保证的。</p>
<p>并且volatile关键字能保证，执行到语句3时，语句1和语句2必定是执行完毕了的，且语句1和语句2的执行结果对语句3、语句4、语句5是可见的。</p>
<p>我们在看看一个例子:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//线程1:</span></span><br><span class="line"><span class="type">ApplicationConext</span> <span class="variable">context</span> <span class="operator">=</span> loadContext();   <span class="comment">//语句1</span></span><br><span class="line"><span class="type">boolean</span> <span class="variable">inited</span> <span class="operator">=</span> <span class="literal">true</span>;             <span class="comment">//语句2</span></span><br><span class="line"><span class="comment">//线程2:</span></span><br><span class="line"><span class="keyword">while</span>(!inited )&#123;</span><br><span class="line">  sleep()</span><br><span class="line">&#125;</span><br><span class="line">doSomethingwithconfig(context);</span><br></pre></td></tr></table></figure>

<p>上述代码有可能语句2会在语句1之前执行，因为语句2并不依赖依赖语句2，可能会重排序优化，那么久可能导致context还没被初始化，而线程2中就使用未初始化的context去进行操作，导致程序出错。</p>
<p>这里如果用volatile关键字对inited变量进行修饰，就不会出现这种问题了，因为当执行到语句2时，必定能保证context已经初始化完毕。</p>
<h2 id="对变量特殊的定义规则"><a href="#对变量特殊的定义规则" class="headerlink" title="对变量特殊的定义规则"></a>对变量特殊的定义规则</h2><p>假设T表示一个线程，V和W表示两个volatile变量，那么在进行read、load、use、assign、store和write操作时需要满足如下的规则:</p>
<ul>
<li>只有一个当线程T对变量V执行的前一个动作是load的时候，T才能对变量V执行use动作，并且当对V的后一个执行是use动作时，T才能对V执行load动作。T对V的use动作其实是衔接T对V的load和read动作，load、read必须一起连续出现（这条规则要求在工作内存每次使用V前都必须先从主内存刷新最新值，使得保证能看见其他线程对变量V的最新更改）。</li>
<li>只有一个当线程T对变量V执行的前一个动作是assign的时候，T才能对变量V执行store动作，并且当对V的后一个执行是store动作时，T才能对V执行assign动作。T对V的assign动作其实是衔接T对V的store和write动作，store、write必须一起连续出现（这条规则要求在工作内存每次修改V后都必须先必须同步到主内中，使得保证其他线程能看见TT对变量V的最新更改）。</li>
<li>假设动作A是线程T对变量VV实施的use或assign动作，假定动作F是与动作A相关联的load和store动作，假定动作PP是与动作FF相应的对V的read和load动作；类似地，假定动作B是线程TT对变量W实施的use和assign动作，假定动作GG是和动作BB相关联的load或store动作，假定动作Q是与动作G相应的对变量W的read和write动作。如果A先于B，那么P先于Q（这条规则要求volatile修饰的变量不会被指令重排序优化，保证代码的执行顺序与程序的顺序相同），即是Happen-before原则。</li>
</ul>
<h2 id="内存屏障其volatile原理"><a href="#内存屏障其volatile原理" class="headerlink" title="内存屏障其volatile原理"></a>内存屏障其volatile原理</h2><h3 id="内存屏障定义"><a href="#内存屏障定义" class="headerlink" title="内存屏障定义"></a>内存屏障定义</h3><p>在研究volatile原理时候，我们来谈谈内存屏障或者内存栅栏。</p>
<p>内存屏障/内存栅栏(Memory Barrier或Menory Fence):重排序时不能把后面的指令重排序到内存屏障之前的位置，指令重排序无法越过内存屏障，单例模式的DCL双锁检查可以体现出来。</p>
<p>只有一个CPU访问内存时，并不需要内存屏障，但如果有多个CPU访问同一块内存，且其中有一个在观测另一个，就需要内存屏障来保证一致。</p>
<p>从硬件架构上讲，指令重排序是指CPU采取可允许将多条指令不按程序规定的顺序分开发送给各相应单路处理单元。但并不是指令任意重排，CPU需要能正确处理指令依赖情况以保障程序能够得出正确的执行结果。</p>
<p>由于现代的操作系统都是多处理器.而每一个处理器都有自己的缓存,并且这些缓存并不是实时都与内存发生信息交换.这样就可能出现一个cpu上的缓存数据与另一个cpu上的缓存数据不一致的问题。而这样在多线程开发中，就有可能导致出现一些异常行为。而操作系统底层为了这些问题，提供了一些内存屏障用以解决这样的问题，目前有4种屏障：</p>
<ul>
<li>LoadLoad屏障：对于这样的语句Load1; LoadLoad; Load2，在Load2及后续读取操作要读取的数据被访问前，保证Load1要读取的数据被读取完毕。</li>
<li>StoreStore屏障：对于这样的语句Store1; StoreStore; Store2，在Store2及后续写入操作执行前，保证Store1的写入操作对其它处理器可见。</li>
<li>LoadStore屏障：对于这样的语句Load1; LoadStore; Store2，在Store2及后续写入操作被刷出前，保证Load1要读取的数据被读取完毕。</li>
<li>StoreLoad屏障：对于这样的语句Store1; StoreLoad; Load2，在Load2及后续所有读取操作执行前，保证Store1的写入对所有处理器可见。它的开销是四种屏障中最大的。在大多数处理器的实现中，这个屏障是个万能屏障，兼具其它三种内存屏障的功能。</li>
</ul>
<h3 id="内存屏障JAVA应用"><a href="#内存屏障JAVA应用" class="headerlink" title="内存屏障JAVA应用"></a>内存屏障JAVA应用</h3><ul>
<li>通过 Synchronized关键字包住的代码区域,当线程进入到该区域读取变量信息时，保证读到的是最新的值。这是因为在同步区内对变量的写入操作，在离开同步区时就将当前线程内的数据刷新到内存中,而对数据的读取也不能从缓存读取,只能从内存中读取,保证了数据的读有效性，这就是插入了StoreStore屏障。</li>
<li>使用了volatile修饰变量,则对变量的写操作，会插入StoreLoad屏障。</li>
<li>其余的操作,则需要通过Unsafe这个类来执行。UNSAFE.putOrderedObject类似这样的方法,会插入StoreStore内存屏障，Unsafe.putVolatiObject 则是插入了StoreLoad屏障</li>
</ul>
<h2 id="适用场景"><a href="#适用场景" class="headerlink" title="适用场景"></a>适用场景</h2><p> 由于volatile变量只保证可见性,在不符合以下两点，我们仍然要通过加锁(使用同步锁synchronize或java.util.concurrent中的原子类)来保证原子性。</p>
<ul>
<li>运算结果以及对变量的写操作并不依赖变量的当前值，或能够确保只有单一的线程修改变量的值；</li>
<li>变量不需要与其他的状态变量共享参与不变约束；</li>
<li>适用于读多写少的场景;</li>
<li>可用作状态标志。</li>
</ul>
<p>JDK中volatie应用：JDK中ConcurrentHashMap的Node的val和next被声明为volatile，AtomicInteger等原子类中的value被声明为volatile。AtomicInteger通过CAS原理(暂可理解为乐观锁)保证了原子性。这些应用后文讲解。</p>
<h2 id="volatile与synchronized"><a href="#volatile与synchronized" class="headerlink" title="volatile与synchronized"></a>volatile与synchronized</h2><p>上述说到的volatile的语义问题，其实volatile变量读操作的性能与普通变量几乎没有什么差别，但是写操作会稍慢点，因为volatile需要在执行中插入许多内存屏障指令来保证处理器不发生乱序执行。</p>
<ul>
<li>在某些情况下volatile的同步机制的性能的确要优于锁(synchronize同步锁或J.U.C包的锁)，但是JDK1.6以后对锁实行了许多消除和优化，使得我们很难量化认为volatile比锁快多少。</li>
<li>多线程访问volatile不会发生阻塞，而synchronized会阻塞；</li>
<li>volatile只能保证数据的可见性，不能保证原子性，而synchronized两者都可以保证，因为它会将私有内存和公共内存中的数据做同步</li>
</ul>
<h2 id="对long和double型变量的特殊规则"><a href="#对long和double型变量的特殊规则" class="headerlink" title="对long和double型变量的特殊规则"></a>对long和double型变量的特殊规则</h2><p>内存的八个操作虽然说都是原子性的，但是对于64位的数据类型：long和double来讲，允许虚拟机将没有被volatile修饰的64位数据的读写操作划分为两次32位的操作来进行，这就是所谓的long和double的非原子性协定。虽然规定为规定，但是目前大部分商业虚拟机将这两种数据类型作64位的原子性操作对待，因为我们不需要将long和double类型的变量专门什么为volatile变量。</p>
<h2 id="参考资料"><a href="#参考资料" class="headerlink" title="参考资料"></a>参考资料</h2><ul>
<li>《深入理解Java虚拟机（第2版）》周志明著</li>
<li>《Java多线程编程核心技术》高洪岩著</li>
</ul>
</section>
    <!-- Tags START -->
    
      <div class="tags">
        <span>Tags:</span>
        
  <a href="/tags#JVM及并发编程" >
    <span class="tag-code">JVM及并发编程</span>
  </a>

      </div>
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2018/06/01/%E3%80%90Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E5%AE%9E%E6%88%98%E3%80%91-Java%E5%86%85%E5%AD%98%E6%A8%A1%E5%9E%8B/">
        <span class="nav-arrow">← </span>
        
          【Java并发编程实战】-Java内存模型
        
      </a>
    
    
      <a class="nav-right" href="/2018/06/08/%E3%80%90Java%E5%B9%B6%E5%8F%91%E7%BC%96%E7%A8%8B%E5%AE%9E%E6%88%98%E3%80%91-Java%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%9F%BA%E7%A1%80/">
        
          【Java并发编程实战】-Java线程池基础
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">若你觉得我的文章对你有帮助，欢迎点击上方按钮对我打赏</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Utterances START -->
      <div id="utterances"></div>
      <script src="https://utteranc.es/client.js"
        repo="ltyeamin/blogtalks"
        issue-term="pathname"
        theme="github-light"
        crossorigin="anonymous"
        async></script>    
      <!-- Utterances END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E4%B8%A4%E7%A7%8D%E7%89%B9%E6%80%A7"><span class="toc-nav-text">两种特性</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E7%89%B9%E6%80%A7%E5%BD%92%E7%BA%B3"><span class="toc-nav-text">特性归纳</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E4%BB%A3%E7%A0%81%E7%A4%BA%E4%BE%8B"><span class="toc-nav-text">代码示例</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%B9%B6%E5%8F%91%E5%AE%89%E5%85%A8"><span class="toc-nav-text">多线程并发安全</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#%E7%A6%81%E6%AD%A2%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92%E5%BA%8F"><span class="toc-nav-text">禁止指令重排序</span></a></li></ol></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%AF%B9%E5%8F%98%E9%87%8F%E7%89%B9%E6%AE%8A%E7%9A%84%E5%AE%9A%E4%B9%89%E8%A7%84%E5%88%99"><span class="toc-nav-text">对变量特殊的定义规则</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%86%85%E5%AD%98%E5%B1%8F%E9%9A%9C%E5%85%B6volatile%E5%8E%9F%E7%90%86"><span class="toc-nav-text">内存屏障其volatile原理</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E5%86%85%E5%AD%98%E5%B1%8F%E9%9A%9C%E5%AE%9A%E4%B9%89"><span class="toc-nav-text">内存屏障定义</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#%E5%86%85%E5%AD%98%E5%B1%8F%E9%9A%9CJAVA%E5%BA%94%E7%94%A8"><span class="toc-nav-text">内存屏障JAVA应用</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E9%80%82%E7%94%A8%E5%9C%BA%E6%99%AF"><span class="toc-nav-text">适用场景</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#volatile%E4%B8%8Esynchronized"><span class="toc-nav-text">volatile与synchronized</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%AF%B9long%E5%92%8Cdouble%E5%9E%8B%E5%8F%98%E9%87%8F%E7%9A%84%E7%89%B9%E6%AE%8A%E8%A7%84%E5%88%99"><span class="toc-nav-text">对long和double型变量的特殊规则</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#%E5%8F%82%E8%80%83%E8%B5%84%E6%96%99"><span class="toc-nav-text">参考资料</span></a></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://example.com/2018/06/03/【Java并发编程实战】-浅谈volatile内存可见性/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', '/css/images/error_icon.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== '/css/images/error_icon.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>






    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    &copy; 2024 | Proudly powered by <a href="https://hexo.io" target="_blank">Hexo</a>
    <br>
    Theme by <a target="_blank" rel="noopener" href="https://github.com/ltyeamin">tong.li</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("https://cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("https://cdn.staticfile.org/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      hljs.configure({useBR: true});
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->



<script src='https://cdn.staticfile.org/mermaid/8.11.2/mermaid.min.js'></script>



<script src="/js/script.js"></script>


  </body>
</html>